using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinLOAtest.Data;
using WinLOAtest.Models;

namespace WinLOAtest.Forms
{
    public partial class AccountManagementForm : Form
    {
        private List<Account> accounts;
        private List<FeatureConfig> features;
        private Account currentAccount;

        public AccountManagementForm()
        {
            InitializeComponent();
            LoadData();
        }

        /// <summary>
        /// 加载数据
        /// </summary>
        private void LoadData()
        {
            try
            {
                accounts = DatabaseHelper.GetAllAccounts();
                features = DatabaseHelper.GetAllFeatureConfigs();
                RefreshAccountList();
                RefreshFeatureCheckBoxes();
                RefreshFeatureComboBox();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新账号列表
        /// </summary>
        private void RefreshAccountList()
        {
            listViewAccounts.Items.Clear();
            foreach (var account in accounts)
            {
                var item = new ListViewItem(account.AccountName);
                item.SubItems.Add(account.FeatureString);
                item.SubItems.Add(account.CreateTime.ToString("yyyy-MM-dd HH:mm"));
                item.SubItems.Add(account.Remark);
                item.Tag = account;
                listViewAccounts.Items.Add(item);
            }
        }

        /// <summary>
        /// 刷新功能复选框
        /// </summary>
        private void RefreshFeatureCheckBoxes()
        {
            panelFeatures.Controls.Clear();
            
            // 创建4列5行的布局
            int colCount = 4;
            int rowCount = 5;
            int checkBoxWidth = 150;
            int checkBoxHeight = 30;
            int margin = 10;

            for (int i = 0; i < 20; i++)
            {
                var feature = features.FirstOrDefault(f => f.FeatureId == i + 1);
                if (feature != null)
                {
                    var checkBox = new CheckBox
                    {
                        Text = $"{feature.FeatureName}",
                        Tag = feature.FeatureId,
                        Width = checkBoxWidth,
                        Height = checkBoxHeight,
                        Location = new Point(
                            (i % colCount) * (checkBoxWidth + margin) + margin,
                            (i / colCount) * (checkBoxHeight + margin) + margin
                        )
                    };
                    checkBox.CheckedChanged += FeatureCheckBox_CheckedChanged;
                    panelFeatures.Controls.Add(checkBox);
                }
            }
        }

        /// <summary>
        /// 刷新功能下拉框
        /// </summary>
        private void RefreshFeatureComboBox()
        {
            comboBoxFeatures.Items.Clear();
            foreach (var feature in features.OrderBy(f => f.SortOrder))
            {
                comboBoxFeatures.Items.Add(feature);
            }
        }

        /// <summary>
        /// 功能复选框状态改变事件
        /// </summary>
        private void FeatureCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (currentAccount != null)
            {
                UpdateAccountFeatureString();
            }
        }

        /// <summary>
        /// 更新账号功能字符串
        /// </summary>
        private void UpdateAccountFeatureString()
        {
            if (currentAccount == null) return;

            var enabledFeatures = new List<int>();
            foreach (Control control in panelFeatures.Controls)
            {
                if (control is CheckBox checkBox && checkBox.Checked)
                {
                    enabledFeatures.Add((int)checkBox.Tag);
                }
            }

            currentAccount.FeatureString = Form1.GenerateBinaryString(enabledFeatures, 20);
            textBoxFeatureString.Text = currentAccount.FeatureString;
        }

        /// <summary>
        /// 新增账号按钮点击事件
        /// </summary>
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            ClearForm();
            currentAccount = new Account();
            textBoxAccountName.Focus();
        }

        /// <summary>
        /// 保存账号按钮点击事件
        /// </summary>
        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBoxAccountName.Text))
            {
                MessageBox.Show("请输入账号名称！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textBoxAccountName.Focus();
                return;
            }

            try
            {
                currentAccount.AccountName = textBoxAccountName.Text.Trim();
                currentAccount.Remark = textBoxRemark.Text.Trim();
                UpdateAccountFeatureString();

                bool success;
                if (currentAccount.Id == 0)
                {
                    // 新增
                    success = DatabaseHelper.AddAccount(currentAccount);
                    if (success)
                    {
                        MessageBox.Show("账号添加成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    // 更新
                    success = DatabaseHelper.UpdateAccount(currentAccount);
                    if (success)
                    {
                        MessageBox.Show("账号更新成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }

                if (success)
                {
                    LoadData();
                    ClearForm();
                }
                else
                {
                    MessageBox.Show("操作失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"操作失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 删除账号按钮点击事件
        /// </summary>
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (currentAccount == null || currentAccount.Id == 0)
            {
                MessageBox.Show("请选择要删除的账号！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (MessageBox.Show($"确定要删除账号 '{currentAccount.AccountName}' 吗？", "确认删除", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    bool success = DatabaseHelper.DeleteAccount(currentAccount.Id);
                    if (success)
                    {
                        MessageBox.Show("账号删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        LoadData();
                        ClearForm();
                    }
                    else
                    {
                        MessageBox.Show("删除失败！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        /// <summary>
        /// 清空表单
        /// </summary>
        private void ClearForm()
        {
            currentAccount = null;
            textBoxAccountName.Clear();
            textBoxRemark.Clear();
            textBoxFeatureString.Clear();
            
            foreach (Control control in panelFeatures.Controls)
            {
                if (control is CheckBox checkBox)
                {
                    checkBox.Checked = false;
                }
            }
        }

        /// <summary>
        /// 账号列表选择改变事件
        /// </summary>
        private void listViewAccounts_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewAccounts.SelectedItems.Count > 0)
            {
                currentAccount = (Account)listViewAccounts.SelectedItems[0].Tag;
                LoadAccountToForm();
            }
        }

        /// <summary>
        /// 加载账号到表单
        /// </summary>
        private void LoadAccountToForm()
        {
            if (currentAccount == null) return;

            textBoxAccountName.Text = currentAccount.AccountName;
            textBoxRemark.Text = currentAccount.Remark;
            textBoxFeatureString.Text = currentAccount.FeatureString;

            // 设置功能复选框状态
            foreach (Control control in panelFeatures.Controls)
            {
                if (control is CheckBox checkBox)
                {
                    int featureId = (int)checkBox.Tag;
                    checkBox.Checked = currentAccount.FeatureString[featureId - 1] == '1';
                }
            }
        }

        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            string searchText = textBoxSearch.Text.Trim();
            if (string.IsNullOrEmpty(searchText))
            {
                RefreshAccountList();
                return;
            }

            listViewAccounts.Items.Clear();
            var filteredAccounts = accounts.Where(a => 
                a.AccountName.Contains(searchText) || 
                a.Remark.Contains(searchText)).ToList();

            foreach (var account in filteredAccounts)
            {
                var item = new ListViewItem(account.AccountName);
                item.SubItems.Add(account.FeatureString);
                item.SubItems.Add(account.CreateTime.ToString("yyyy-MM-dd HH:mm"));
                item.SubItems.Add(account.Remark);
                item.Tag = account;
                listViewAccounts.Items.Add(item);
            }
        }

        /// <summary>
        /// 按功能查询按钮点击事件
        /// </summary>
        private void buttonSearchByFeature_Click(object sender, EventArgs e)
        {
            if (comboBoxFeatures.SelectedItem == null)
            {
                MessageBox.Show("请选择要查询的功能！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            var selectedFeature = (FeatureConfig)comboBoxFeatures.SelectedItem;
            try
            {
                var accountsWithFeature = DatabaseHelper.GetAccountsByFeature(selectedFeature.FeatureId);
                
                listViewAccounts.Items.Clear();
                foreach (var account in accountsWithFeature)
                {
                    var item = new ListViewItem(account.AccountName);
                    item.SubItems.Add(account.FeatureString);
                    item.SubItems.Add(account.CreateTime.ToString("yyyy-MM-dd HH:mm"));
                    item.SubItems.Add(account.Remark);
                    item.Tag = account;
                    listViewAccounts.Items.Add(item);
                }

                MessageBox.Show($"找到 {accountsWithFeature.Count} 个拥有 '{selectedFeature.FeatureName}' 功能的账号。", 
                    "查询结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 刷新按钮点击事件
        /// </summary>
        private void buttonRefresh_Click(object sender, EventArgs e)
        {
            LoadData();
            textBoxSearch.Clear();
        }
    }
}
